package com.leyou.user.service;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.utils.RegexUtils;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.mapper.UserMapper;
import com.leyou.user.pojo.User;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.leyou.common.constants.MQConstants.Exchange.SMS_EXCHANGE_NAME;
import static com.leyou.common.constants.MQConstants.RoutingKey.VERIFY_CODE_KEY;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private AmqpTemplate amqpTemplate;
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    private static final String KEY_PREFIX = "user:verify:phone:";

    public Boolean checkData(String data, Integer type) {
        User record = new User();
        // 条件判断
        switch (type) {
            case 1:
                // 用户名
                record.setUsername(data);
                break;
            case 2:
                // 手机
                record.setPhone(data);
                break;
            default:
                throw new LyException(ExceptionEnum.INVALID_PARAM_ERROR);
        }

        // 0：当前用户名或者手机号码还没有注册
        return userMapper.selectCount(record) == 0;
    }

    public void sendCode(String phone) {
        // 服务端接收，并验证手机号码
        if (!RegexUtils.isPhone(phone)) {
            throw new LyException(ExceptionEnum.INVALID_PHONE_NUMBER);
        }
        // 生成随机验证码
        String code = RandomStringUtils.randomNumeric(6);
        // 存储验证码到redis，保存时间为5分钟
        redisTemplate.opsForValue().set(KEY_PREFIX + phone, code, 5, TimeUnit.MINUTES);
        // 发送给ly-sms
        Map<String, String> map = new HashMap<>();
        map.put("phone", phone);
        map.put("code", code);
        // 发送信息到mq
        amqpTemplate.convertAndSend(SMS_EXCHANGE_NAME, VERIFY_CODE_KEY, map);
    }

    public void register(User user, String code) {
        // 校验验证码 取出Redis的验证码
        String cachCode = redisTemplate.opsForValue().get(KEY_PREFIX + user.getPhone());
        // 比较验证码
        if (!StringUtils.equals(code, cachCode)) {
            throw new LyException(ExceptionEnum.INVALID_VERIFY_CODE);
        }
        // 对密码加密
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        // 写入数据库
        int count = userMapper.insertSelective(user);
        if (count != 1) {
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }
    }

    public UserDTO queryByUsernameAndPassword(String username, String password) {
        // 创建用户对象设置用户名
        User record = new User();
        record.setUsername(username);
        // 查询用户
        User user = userMapper.selectOne(record);
        if (user == null) {
            // 用户不存在
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }
        // 用户存在，判断两次密码是否一致
        if (!passwordEncoder.matches(password, user.getPassword())) {
            // 密码不一致
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }
        // 校验成功返回用户dto
        return BeanHelper.copyProperties(user, UserDTO.class);
    }
}
